﻿using AutoMapper;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Data;
using Microsoft.Extensions.Logging;
using ShanNiang.Mvvm.UiServices;
using ShanNiang.Service;
using ShanNiang.Service.Enumerate;
using ShanNiang.Service.Implementations;
using ShanNiang.Service.Interfaces;
using ShanNiang.Service.Scaner;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShanNiang.Mvvm.ViewModels
{
    public abstract partial class ScannableViewModel : UIViewModel
    {
        protected ScannableViewModel(PackingConfig packingConfig, IScanerService scanerService,IUiService uiService,
            IMapper mapper, ILogger<ScannableViewModel> logger) : base(mapper, logger)
        {
            PackingConfig = packingConfig;
            ScanerService = scanerService;
            UiService = uiService;
        }

        /// <summary>
        /// UI正在扫码中。。
        /// </summary>
        [ObservableProperty]
        private bool _scanning;
        /// <summary>
        /// 扫码服务
        /// </summary>
        protected IScanerService ScanerService { get; private set; }
        /// <summary>
        /// 配置
        /// </summary>
        protected PackingConfig PackingConfig { get; private set; }

        protected IUiService UiService { get; private set; }

        /// <summary>
        /// 扫码回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual async void ScanerService_CodeScanedAsync(object? sender, CodeEventArgs e) 
        {
            Scanning = true;
            try
            {
                await CodeScanedAsync(sender, e);
            }
            catch (Exception ex)
            {
                UiService.GrowlError(ex.Message, CodeType.Unknown);
            }
            finally
            {
                Scanning = false;
            }
        }
        /// <summary>
        /// 内部扫码回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected abstract Task CodeScanedAsync(object? sender, CodeEventArgs e);
        /// <summary>
        /// 页面加载
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        protected virtual async Task LoadedAsync()
        {
            ScanerService.CodeScaned += ScanerService_CodeScanedAsync;
            ScanerService.Start();
            await Task.CompletedTask;
        }
        /// <summary>
        /// 页面被卸载
        /// </summary>
        [RelayCommand]
        protected virtual void Unloaded()
        {
            ScanerService.CodeScaned -= ScanerService_CodeScanedAsync;
            ScanerService.Stop();
        }
    }
}
